package com.example.fundamentallibrary

import com.google.gson.JsonParseException
import io.reactivex.rxjava3.core.Observer
import io.reactivex.rxjava3.disposables.Disposable
import org.json.JSONException
import retrofit2.HttpException
import java.io.InterruptedIOException
import java.net.ConnectException
import java.net.UnknownHostException
import java.text.ParseException

abstract class DefaultObserver<T> : Observer<T> {
    override fun onSubscribe(d: Disposable?) {

    }

    override fun onNext(t: T) {
        onSuccess(t)
    }

    override fun onError(e: Throwable?) {
        when (e) {
            is HttpException -> {
                onException(ExceptionReason.BAD_NETWORK)
            }
            is ConnectException, is UnknownHostException -> {
                onException(ExceptionReason.CONNECT_ERROR)
            }
            is InterruptedIOException -> {
                onException(ExceptionReason.CONNECT_TIMEOUT)
            }
            is JsonParseException, is JSONException, is ParseException -> {
                onException(ExceptionReason.PARSE_ERROR)
            }
            else -> {
                onException(ExceptionReason.UNKNOWN_ERROR)
            }
        }
        onFailed(e)
    }

    override fun onComplete() {

    }

    abstract fun onSuccess(response: T)

    fun onFailed(e: Throwable?) {

    }

    fun onException(reason: ExceptionReason) {
        when (reason) {

        }
    }
}